
import Logging from "./logging";

const baseURL = "http://119.23.243.5:8080/";
const	baseAPIURL = baseURL + "test/";
const baseMedia = baseURL;

const method = {
	get: "GET",
	put: "PUT",
	head: "HEAD",
	post: "POST",
	trace: "TRACE",
	delete: "DELETE",
	connect: "CONNECT",
	options: "OPTIONS",
};

const config = {
	data: {},
	header: {
		"Content-Type": "application/x-www-form-urlencoded",
	},
	timeout: 0,
	method: method.get,
	dataType: "json",
	responseType: "text",
	// `baseURL` 将自动加在 `url` 前面，除非 `url` 是一个绝对 URL
	baseURL: baseAPIURL,
	// 请求失败
	fail: () => {},
	// 请求之后
	after: () => {},
	// 请求之前
	before: () => {},
	// 请求成功
	success: () => {},
	// 请求结束
	complete: () => {},
};

function getToken() {
	return wx.getStorageSync("token") || "";
}

function setToken(v) {
	wx.setStorageSync("token", v);
}

function request(params = {}) {
	let param = Object.assign({}, config, params);
	param.url = toAbs(param.url, param.baseURL);
	param.header.token = getToken();
	
	const fail = param.fail;
	const after = param.after;
	const before = param.before;
	const success = param.success;
	const complete = param.complete;

	before();
	param.success = (res) => {
		const statusCode = res.statusCode;
		const code = res.data.code;

		after();

		const token = res.header["token"];
		if (token) {
			setToken(token);
		}

		if (200 !== statusCode) {
			fail(res);
		}

		if (110007 == code) {
			// hander_110007();
		}

		if (200 == code) {
			return success(res);
		}

		fail(res);
	};

	param.fail = (res) => {
		after();
		fail(res);
	};

	param.complete = (res) => {
		complete(res);
	};

	return wx.request(param);
}

function hander_110007() {
	if (Logging.get()) {
		return;
	}
	Logging.set(true);

	wx.reLaunch({url: "/pages/user/login/index"});
}


function post(params = {}) {
	params.method = method.post;
	return request(params);
}

function get(params = {}) {
	params.method = method.get;
	return request(params);
}

/**
 * 获取绝对地址
 * @param {String} base 基
 * @param {String} val	值
 */
function toAbs(val, base = baseMedia) {
	val = String(val);
	if (val.startsWith("http")) {
		return val;
	}
	if (val.startsWith("/")) {
		val = val.substr(1);
	}
	return base + val;
}

/**
 * 获取相对地址
 * @param {String} base  基
 * @param {String} val   值
 */
function toRel(val, base = baseMedia) {
	val = String(val);
	if (val.startsWith(base)) {
		val = val.replace(base, "");
	}
	if (false == val.startsWith("/")) {
		val = "/" + val;
	}
	return val;
}

export {
	baseURL,
	baseAPIURL,
	baseMedia,
	request,
	post,
	get,
	toAbs,
	toRel,
};

export default {
	baseURL,
	baseAPIURL,
	baseMedia,
	request,
	post,
	get,
	toAbs,
	toRel,
};